#!/usr/bin/env python
#-*-encoding:utf-8-*-
'''
Created on 2015年3月10日

@author: chenyongbing
'''
import sys,os
#current_dir = os.path.dirname(__file__)
current_dir = os.path.split(os.path.realpath(__file__))[0]

from django.http import HttpResponse,HttpResponseNotFound
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils import simplejson 
from django.contrib.auth.decorators import login_required  
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import render
import logging
import re,os,datetime

from ap_infos import APInfos

myAPInfos = APInfos()
from forms import *
sys.path.append(os.path.join(current_dir,'../../'))
from base.form_datas import FormDatas
myFormDatas = FormDatas()

from base.retail_datas import myRetailDatas


def show_ap_status_by_comp(request):
 
    logging.debug(request)
    myForm = CompAndGroupSelectForm()
    if request.method=='POST':
        if request.POST.has_key('company') and request.POST.has_key('group') and request.POST.has_key('fields') :
            comp_id = request.POST['company']
            group = request.POST['group']
            fields  = dict(request.POST)['fields']
        else:
            comp_id = 'company'
            group = group
            fields = ['group_name','device','status']
    else:
        comp_id = 'company'
        group = 'group'
        fields = ['group_name','device','status']
        
   
    myForm.initial = {'company':comp_id,'group':group,'fields':fields}
    if comp_id=='company':comp_id=None
    if group == 'group' : group=None
    companies = myFormDatas.get_companies_data()
    if comp_id!=None:
        groups = myFormDatas.get_groups_data(comp_id=comp_id)
    else:
        groups = []
    myForm.fields['company'].choices +=companies
    myForm.fields['group'].choices +=groups
    
    if group==None and comp_id==None:
        groups = []
    elif group==None:
        groups = myRetailDatas.get_groups_by_comp(comp_id=comp_id)
    else:
        groups = [group]
    if len(groups)>0:
        devices = myRetailDatas.get_devices_by_groups(groups)
    else:
        devices = []
    
    datas = myAPInfos.get_ap_infos(devices=devices,fields=fields)
    fieldNames = get_field_name(myForm.Fields, fields)
    
    return render_to_response(u'zmAPMonitor/comp_ap_status.html',{'datas':datas,'myForm':myForm,'fields':fields,'fieldNames':fieldNames},context_instance=RequestContext(request))
    
def get_field_name(FieldInfos = [],fields=[]):
    fieldNames = []
    for field , name in FieldInfos:
        if field in fields:
            fieldNames.append(name)
    return fieldNames
def show_ap_status_by_comp_with_version(request):
    logging.debug(request)
    myForm = CompAndGroupSelectForm()
    if request.method=='POST':
        if request.POST.has_key('company') and request.POST.has_key('group'):
            comp_id = request.POST['company']
            group = request.POST['group']
        else:
            comp_id = 'company'
            group = group
    else:
        comp_id = 'company'
        group = 'group'
    myForm.initial = {'company':comp_id,'group':group}
    if comp_id=='company':comp_id=None
    if group == 'group' : group=None
    companies = myFormDatas.get_companies_data()
    if comp_id!=None:
        groups = myFormDatas.get_groups_data(comp_id=comp_id)
    else:
        groups = []
    myForm.fields['company'].choices +=companies
    myForm.fields['group'].choices +=groups
    if group==None and comp_id==None:
        groups = []
    elif group==None:
        groups = myRetailDatas.get_groups_by_comp(comp_id=comp_id)
    else:
        groups = [group]
    if len(groups)>0:
        devices = myRetailDatas.get_devices_by_groups(groups)
    else:
        devices = []
    print devices
    datas = myAPInfos.get_ap_infos(devices=devices)
    return render_to_response(u'zmAPMonitor/comp_ap_status_with_version.html',{'datas':datas,'myForm':myForm},context_instance=RequestContext(request))
    

    
def show_ap_status(request):
    devices = []
    if request.method=='POST':
        if request.POST.has_key('devices'):
            devicesStr = request.POST['devices']
            for devStr in devicesStr.split('\n'):
                device = re.sub('[^a-z0-9]','',devStr.lower())
                if len(device)!=12 and len(device)!=10:continue
                devices.append(device)
    if devices==[]:
        return render_to_response(u'zmAPMonitor/ap_status.html',{},context_instance=RequestContext(request))
    else:
        datas = myAPInfos.get_ap_infos(devices=devices)
        return render_to_response(u'zmAPMonitor/ap_status.html',{'datas':datas,'devices':devicesStr},context_instance=RequestContext(request))



from base.retail_datas import myRetailDatas
def show_device_relegation(request):
    devices = []
    if request.method=='POST':
        if request.POST.has_key('devices'):
            devicesStr = request.POST['devices']
            for devStr in devicesStr.split('\n'):
                device = re.sub('[^a-z0-9]','',devStr.lower())
                if len(device)!=12 and len(device)!=10:continue
                devices.append(device)
    if devices==[]:
        return render_to_response(u'zmAPMonitor/ap_relegation.html',{},context_instance=RequestContext(request))
    else:
        datas = myRetailDatas.get_devices_comp_info(devices)
        return render_to_response(u'zmAPMonitor/ap_relegation.html',{'datas':datas,'devices':devicesStr},context_instance=RequestContext(request))




from record_ap_online_time import myRecordStaOnlineTime

def show_ap_online_time(request):
    devices = []
    myForm = ExportApOnlineTimeForm()
    if request.method=='POST':
        cate = request.POST['cate']
        prov = request.POST['province']
        city = request.POST['city']
        dist = request.POST['dist']
        comp_id = request.POST['company']
        group = request.POST['group']
        startTime = request.POST['startTime']
        endTime = request.POST['endTime']

    else:
        cate = myForm.fields['cate'].choices[0][0]
        prov = myForm.fields['province'].choices[0][0]
        city = myForm.fields['city'].choices[0][0]
        dist = myForm.fields['dist'].choices[0][0]
        comp_id=myForm.fields['company'].choices[0][0]
        group = myForm.fields['group'].choices[0][0]
        startTime = ''
        endTime = ''
    initial={'cate':cate,'province':prov,'city':city,'dist':dist,'company':comp_id,'group':group,'startTime':startTime,'endTime':endTime}
    myForm.initial = initial
    myForm = myFormDatas.export_base_feild_form(request,myForm,initial)
    if prov=='province':prov = None
    if cate == 'cate':cate= None
    if comp_id=='company':comp_id=None
    if city == 'city':city = None
    if dist == 'dist':dist=None
    if group == 'group':group = None
    
    gdatas = None
    if comp_id!=None or prov!=None or cate!=None:
        gdatas = myFormDatas.get_groups_data(comp_id=comp_id, prov=prov, city=city, dist=dist,cate=cate,shop_group=group)
    if re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',startTime) and re.search('^[\d]{4}-[\d]{2}-[\d]{2}$',endTime) and len(gdatas)>0:
        dgroups = []
        for group_id,group_name in gdatas:
            dgroups.append(group_id)
            
        datas = myRecordStaOnlineTime.get_online_time_datas_with_lenovo_temp(shop_groups=dgroups, startTime=startTime, endTime=endTime)

        fields = datas[0]
    else:
        #hourDatas = [[u'日期',u'星期',u'时间段',u'名称',u'门店',u'品牌',u'店铺编码',u'归属省份',u'归属城市',u'客流量',u'入店量',u'路过客流']]
        #hourDatas = [['日期','星期','时间段','名称','门店','品牌','店铺编码','归属省份','归属城市','客流量','入店量','路过客流']]
        datas = []
        fields = None

    return render_to_response('zmExport/export_hour_data.html',{'form':myForm,'gdatas':gdatas,'hourDatas':simplejson.dumps(datas[1:]),'hourFields':fields},context_instance=RequestContext(request))

